import os
import random
from playwright.sync_api import sync_playwright


class SignChrome:
    def __init__(self):
        self.content = ""
        self.result_flag = False

    def get_sign(self, url, card_num, proxy_url=None, proxy_pre=None):
        proxy = None
        if proxy_url:
            if proxy_pre:
                proxy = {
                    "server": proxy_url,
                    "username": proxy_pre.split(":")[0],
                    "password": proxy_pre.split(":")[0]
                }
            else:
                proxy = {
                    "server": proxy_url
                }
        with sync_playwright() as p:
            browser = p.chromium.launch(headless=True,
                                        proxy=proxy,
                                        args=[
                                            "--disable-blink-features=AutomationControlled",
                                            "--disable-infobars"
                                        ]
                                        )

            def get_random_user_agent():
                agents = [
                    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; AcooBrowser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
                    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; SLCC1; .NET CLR 2.0.50727; "
                ]
                return random.choice(agents)

            def stealth_page(context):
                page = context.new_page()
                page.add_init_script("""
                    Object.defineProperty(navigator, 'webdriver', {
                        get: () => undefined
                    })
                """)
                return page
            context = browser.new_context(
                # user_agent=get_random_user_agent(),
                viewport={"width": 1366, "height": 768}
            )
            page = stealth_page(context)

            page.goto(url)
            page.wait_for_selector('#cxpid')
            page.type('#cxpid', card_num, delay=50)
            page.click('xpath=//*[@id="cxbt"]')
            page.wait_for_selector("#t_signup")
            self.content = page.content()
            browser.close()
        return self.content

    def get_pic(self, url, download_dir, proxy_url=None, proxy_pre=None):
        proxy = None
        if proxy_url:
            if proxy_pre:
                proxy = {
                    "server": proxy_url,
                    "username": proxy_pre.split(":")[0],
                    "password": proxy_pre.split(":")[0]
                }
            else:
                proxy = {
                    "server": proxy_url
                }
        with sync_playwright() as p:
            browser = p.chromium.launch(headless=True,
                                        proxy=proxy,
                                        downloads_path=download_dir,
                                        args=[
                                            "--disable-blink-features=AutomationControlled",
                                            "--disable-infobars"
                                        ]
                                        )

            def get_random_user_agent():
                agents = [
                    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; AcooBrowser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
                    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; SLCC1; .NET CLR 2.0.50727; "
                ]
                return random.choice(agents)

            def stealth_page(context):
                page = context.new_page()
                page.add_init_script("""
                    Object.defineProperty(navigator, 'webdriver', {
                        get: () => undefined
                    })
                """)
                return page
            context = browser.new_context(
                # user_agent=get_random_user_agent(),
                viewport={"width": 1366, "height": 768}
            )
            page = stealth_page(context)

            page.goto(url)
            page.wait_for_timeout(100)
            with page.expect_download() as download_info:
                page.click('xpath=//*[@id="downloadCerti"]')

            download = download_info.value
            pic_url = download.url
            browser.close()
        return pic_url

    def get_pic1(self, url, download_dir, save_path, proxy_url=None, proxy_pre=None):
        pic_flag = False
        proxy = None
        if proxy_url:
            if proxy_pre:
                proxy = {
                    "server": proxy_url,
                    "username": proxy_pre.split(":")[0],
                    "password": proxy_pre.split(":")[0]
                }
            else:
                proxy = {
                    "server": proxy_url
                }
        with sync_playwright() as p:
            browser = p.chromium.launch(headless=True,
                                        proxy=proxy,
                                        downloads_path=download_dir,
                                        args=[
                                            "--disable-blink-features=AutomationControlled",
                                            "--disable-infobars"
                                        ]
                                        )

            def get_random_user_agent():
                agents = [
                    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; AcooBrowser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
                    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; SLCC1; .NET CLR 2.0.50727; "
                ]
                return random.choice(agents)

            def stealth_page(context):
                page = context.new_page()
                page.add_init_script("""
                    Object.defineProperty(navigator, 'webdriver', {
                        get: () => undefined
                    })
                """)
                return page
            context = browser.new_context(
                # user_agent=get_random_user_agent(),
                viewport={"width": 1366, "height": 768}
            )
            page = stealth_page(context)

            page.goto(url)
            page.wait_for_timeout(100)
            with page.expect_download() as download_info:
                page.click('xpath=//*[@class="downloadNumberCloth"]')

            download = download_info.value
            download.save_as(save_path)
            download.delete()
            pic_flag = True
            browser.close()
        return pic_flag

    def get_pic2(self, url, proxy_url=None, proxy_pre=None):
        proxy = None
        if proxy_url:
            if proxy_pre:
                proxy = {
                    "server": proxy_url,
                    "username": proxy_pre.split(":")[0],
                    "password": proxy_pre.split(":")[0]
                }
            else:
                proxy = {
                    "server": proxy_url
                }
        with sync_playwright() as p:
            browser = p.chromium.launch(headless=True,
                                        proxy=proxy,
                                        args=[
                                            "--disable-blink-features=AutomationControlled",
                                            "--disable-infobars"
                                        ]
                                        )

            def get_random_user_agent():
                agents = [
                    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; AcooBrowser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
                    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; SLCC1; .NET CLR 2.0.50727; "
                ]
                return random.choice(agents)

            def stealth_page(context):
                page = context.new_page()
                page.add_init_script("""
                    Object.defineProperty(navigator, 'webdriver', {
                        get: () => undefined
                    })
                """)
                return page
            context = browser.new_context(
                # user_agent=get_random_user_agent(),
                viewport={"width": 1366, "height": 768}
            )
            page = stealth_page(context)

            page.goto(url)
            page.wait_for_timeout(500)
            if "wxxjty.wbs.fit" in url:
                iframe_element = page.wait_for_selector('iframe')
                iframe = iframe_element.content_frame()
            else:
                iframe = page
            img_element = iframe.wait_for_selector('img[src^="data:image"]')
            content = img_element.get_attribute('src')
            browser.close()
        return content

    def get_pic3(self, url, card_num, proxy_url=None, proxy_pre=None):
        proxy = None
        if proxy_url:
            if proxy_pre:
                proxy = {
                    "server": proxy_url,
                    "username": proxy_pre.split(":")[0],
                    "password": proxy_pre.split(":")[0]
                }
            else:
                proxy = {
                    "server": proxy_url
                }
        with sync_playwright() as p:
            browser = p.chromium.launch(headless=True,
                                        proxy=proxy,
                                        args=[
                                            "--disable-blink-features=AutomationControlled",
                                            "--disable-infobars"
                                        ]
                                        )

            def get_random_user_agent():
                agents = [
                    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; AcooBrowser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
                    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; SLCC1; .NET CLR 2.0.50727; "
                ]
                return random.choice(agents)

            def stealth_page(context):
                page = context.new_page()
                page.add_init_script("""
                    Object.defineProperty(navigator, 'webdriver', {
                        get: () => undefined
                    })
                """)
                return page
            context = browser.new_context(
                # user_agent=get_random_user_agent(),
                viewport={"width": 1366, "height": 768}
            )
            page = stealth_page(context)

            page.goto(url)
            page.locator('input').nth(0).type(card_num, delay=50)
            page.click('xpath=//*[@class="van-search__action"]')
            img_element = page.wait_for_selector('img[src^="data:image"]')
            content = img_element.get_attribute('src')
            browser.close()
        return content
# a=SignChrome().get_pic3("https://m.irunner.mobi/runner-master/?match_eng=683518789f82c#/certificate", "371327198604183029")
# pass